/**
 * Created by TamTT on 1/13/14.
 * FPT University - Da Nang
 * Capstone project - group 3
 * Jornee
 */
module.exports.controller = function(app, jwt, secret, db, authentication, util, async, io, log, colors, s3Client){
	/**
	 * Admin login page - TamTT
	 */
	app.get('/this/is/admin/page/for/admin/only', function(req, res){
		log.info('Welcome to Managing Page'.blue);
		res.render('admin_login.ejs', {
			title: 'Jornee'
		});
	});

	/**
	 * Login for admin - TamTT
	 */
	app.post('/admin_login_ajax', function(req, res){
		db.admin.findOne({
			username: req.body.adminName
		}, function(err, user){
			if(err){
				log.error('Admin login - User %s - Error with %s'.red, req.body.adminName, err);
				res.send({
					status: "error"
				});
			}
			if(user != null){
				if(req.body.adminPass == user.password){
					req.session.user_role = "admin";
					req.session.user_name = req.body.adminName;
					log.info('Admin login - User %s - Ok'.blue, req.body.adminName);
					var info = {
						username: req.body.adminName,
						date: new Date()
					};
					var new_token = jwt.encode(info, secret);
					db.admin.update({
						username: req.body.adminName
					}, {
						$set: {
							authentication: new_token
						}
					});
					res.send({
						status: "ok"
					});
				} else {
					log.warning('Admin login - User %s - Wrong login'.yellow, req.body.adminName);
					req.session.user_role = "null";
					res.send({
						status: "fail"
					});
				}
			} else {
				log.warning('Admin login - User %s - Wrong login'.yellow, req.body.adminName);
				req.session.user_role = "null";
				res.send({
					status: "fail"
				});
			}
		});
	});

	/**
	 * Check session for admin - TamTT
	 * @param req
	 */
	function authentication_admin(req){
		if(req.session.user_role != "admin"){
			log.error('Admin authen - User %s - Authen fail. Please relogin!'.red, req.body.adminName);
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Get token - TamTT
	 */
	app.post('/admin_token_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			db.admin.findOne({
				username: req.session.user_name
			}, function(err, admin){
				if(err){
					log.error('Admin token - User %s - Error with %s'.red, req.session.user_name, err);
					res.send({
						status: "error"
					});
				}
				if(admin != null){
					log.info('Admin token - User %s - Ok'.blue, req.session.user_name);
					res.send({
						status: 'ok',
						token: admin.authentication
					});
				} else {
					log.warning('Admin token - User %s - Wrong authen'.yellow, req.session.user_name);
					req.session.user_role = "null";
					res.send({
						status: "error"
					});
				}
			});
		}
	});

	/**
	 * Admin page - TamTT
	 */
	app.get('/this/is/admin/page/for/admin/only/hihi', function(req, res){
		if(!authentication_admin(req)){
			res.redirect('/this/is/admin/page/for/admin/only/');
		} else {
			log.info('Admin page - User %s - Ok'.blue, req.session.user_name);
			var adminName = req.session.user_name;
			res.render('managing.ejs', {
				title: adminName
			});
		}
	});

	/**
	 * Get data summary - TamTT
	 */
	app.post('/statistic_summary_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			db.users.count({}, function(err, user_num){
				if(err){
					log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
					res.send({
						status: 'error'
					});
				} else {
					db.entry.count({}, function(err, entry_num){
						if(err){
							log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
							res.send({
								status: 'error'
							});
						} else {
							db.journey.count({}, function(err, journey_num){
								if(err){
									log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
									res.send({
										status: 'error'
									});
								} else {
									db.place.count({}, function(err, place_num){
										if(err){
											log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
											res.send({
												status: 'error'
											});
										} else {
											db.interestingplace.count({}, function(err, iplace_num){
												if(err){
													log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
													res.send({
														status: 'error'
													});
												} else {
													db.host.count({}, function(err, host_num){
														if(err){
															log.error('Admin statistic summary - User %s - Error with %s'.red, req.session.user_name, err);
															res.send({
																status: 'error'
															});
														} else {
															app.render('statistic_summary.ejs', {
																status: 'ok',
																user_num: user_num,
																entry_num: entry_num,
																journey_num: journey_num,
																place_num: place_num,
																iplace_num: iplace_num,
																host_num: host_num
															}, function(err, html){
																log.info('Admin statistic summary - User %s - Ok - Return: %s'.blue, req.session.user_name, util.inspect({
																	status: 'ok',
																	user_num: user_num,
																	entry_num: entry_num,
																	journey_num: journey_num,
																	place_num: place_num,
																	iplace_num: iplace_num,
																	host_num: host_num
																}));
																res.send({
																	status: 'ok',
																	contents: html
																});
															});
														}
													});
												}
											});
										}
									});
								}
							});
						}
					});
				}
			});
		}
	});

	/**
	 * Get data rank up - TamTT
	 */
	app.post('/statistic_rank_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			db.users.aggregate({
				$sort: {
					create_date: -1
				}
			}, {
				$limit: 1
			}, function(err, newest){
				if(err){
					log.error('Admin statistic rank - User %s - Error with %s'.red, req.session.user_name, err);
					res.send({
						status: 'error'
					});
				} else {
					var newest_user = newest[0];
					if(!newest_user){
						newest_user = {};
						newest_user.username = 'No user yet!';
					}

					// Get user tha have the most follower
					db.users.aggregate({
						$unwind: "$follower"
					}, {
						$group: {
							_id: "$username",
							count: {
								$sum: 1
							}
						}
					}, {
						$sort: {
							count: -1
						}
					}, {
						$limit: 1
					}, function(err, most_followed_result){
						if(err){
							log.error('Admin statistic rank - User %s - Error with %s'.red, req.session.user_name, err);
							res.send({
								status: 'error'
							});
						}
						if(!most_followed_result[0]){ // No result found
							var most_followed = 0;
							var num_most_followers = 0;
						} else {
							var most_followed = most_followed_result[0]._id;
							var num_most_followers = most_followed_result[0].count;
						}
						db.journey.aggregate({
							$unwind: "$liked"
						}, {
							$group: {
								_id: "$_id",
								count: {
									$sum: 1
								}
							}
						}, {
							$sort: {
								count: -1
							}
						}, {
							$limit: 1
						}, {
							$project: {
								_id: 1,
								count: 1
							}
						}, function(err, most_liked_journey_result){
							if(err){
								res.send({
									status: 'error'
								});
							}
							if(!most_liked_journey_result[0]){
								var num_like = 0;
								var journey_search = '';
							} else {
								var num_like = most_liked_journey_result[0].count;
								var journey_search = most_liked_journey_result[0]._id;
							}
							db.journey.findOne({
								_id: journey_search
							}, {
								journey_name: 1,
								_id: 0
							}, function(err, journey){
								if(err){
									res.send({
										status: 'error'
									});
								}
								if(!journey){ // No journey found
									var most_liked_journey = '';
								} else {
									var most_liked_journey = journey.journey_name;
								}

								db.chat.aggregate({
									$unwind: "$conversation"
								}, {
									$group: {
										_id: "$_id",
										count: {
											$sum: 1
										}
									}
								}, {
									$sort: {
										count: -1
									}
								}, {
									$limit: 1
								}, {
									$project: {
										_id: 1,
										count: 1
									}
								}, function(err, longest_conversation_result){
									if(err){
										res.send({
											status: 'error'
										});
									}
									if(!longest_conversation_result[0]){
										var longest_conversation = 0;
									} else {
										var longest_conversation = longest_conversation_result[0].count;
									}
									app.render('statistic_rank.ejs', {
										status: 'ok',
										newest_user: newest_user.username,
										most_followed: most_followed,
										num_most_followers: num_most_followers,
										most_liked_journey: most_liked_journey,
										num_like: num_like,
										longest_conversation: longest_conversation
									}, function(err, html){
										if(err){
											log.error('Admin statistic rank - User %s - Error with %s'.red, req.session.user_name, err);
											res.send({
												status: "error"
											});
										}
										res.send({
											status: 'ok',
											contents: html
										});
									});
								});
							});
						})
					})
				}
			})
		}
	});

	/**
	 * Get user by search result - TamTT
	 */
	app.post('/ultimate_search_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			var keyword = req.body.search_str;
			if(keyword == ''){
				res.send({
					status: 'ok',
					contents: ''
				});
			}

			db.users.find({
				username: keyword
			}, {
				_id: 0,
				username: 1,
				avatar: 1
			}, function(err, exact_users){
				if(err){
					log.error('Admin ultimate search - Admin %s - Error with %s'.red, req.session.user_name, err);
					res.send({
						status: "error"
					});
				} else {
					db.users.find({
						$and: [
							{
								username: {
									$regex: keyword
								}
							},
							{
								username: {
									$ne: keyword
								}
							}
						]
					}, {
						_id: 0,
						username: 1,
						avatar: 1
					}).limit(10, function(err, regex_users){
							if(err){
								log.error('Search friend - User %s - Error with %s'.red, my_id, err);
								res.send({
									authen_status: 'ok',
									status: 'error'
								});
							} else {
								var list_users = exact_users.concat(regex_users);
								app.render('ultimate_search.ejs', {
									status: 'ok',
									list_users: list_users
								}, function(err, html){
									if(err){
										log.error('Admin ultimate search - Admin %s - Error with %s'.red, req.session.user_name, err);
										res.send({
											status: "error"
										});
									}
									res.send({
										status: 'ok',
										contents: html
									});
								});
							}
						}
					);
				}
			});
		}
	});

	/**
	 * Get single user's summary - TamTT
	 */
	app.post('/ultimate_user_summary_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			var user_id = req.body.user_id;
			if(user_id == ''){
				res.send({
					status: 'ok',
					contents: ''
				});
			}
			db.users.findOne({
				username: user_id
			}, {
				_id: 0,
				follower: 1,
				following: 1
			}, function(err, user){
				if(err){
					log.error('Admin ultimate user summary - Admin %s - User %s - Error with %s'.red, req.session.user_name, user_id, err);
					res.send({
						status: "error"
					});
				} else {
					if(!user){
						var num_of_follower = 0;
						var num_of_following = 0;
					} else {
						var num_of_follower = user.follower.length;
						var num_of_following = user.following.length;
					}
					db.entry.count({
						username: user_id
					}, function(err, num_of_entries){
						if(err){
							log.error('Admin ultimate user summary - Admin %s - User %s - Error with %s'.red, req.session.user_name, user_id, err);
							res.send({
								status: "error"
							});
						} else {
							db.journey.count({
								user_id: user_id
							}, function(err, num_of_journey){
								if(err){
									log.error('Admin ultimate user summary - Admin %s - User %s - Error with %s'.red, req.session.user_name, user_id, err);
									res.send({
										status: "error"
									});
								} else {
									db.host.findOne({
										user_id: user_id
									}, {
										_id: 0,
										feedback: 1
									}, function(err, host){
										if(err){
											log.error('Admin ultimate user summary - Admin %s - User %s - Error with %s'.red, req.session.user_name, user_id, err);
											res.send({
												status: "error"
											});
										} else {
											if(!host){
												var num_of_feedback = 0;
											} else {
												if(host.feedback){
													var num_of_feedback = host.feedback.length;
												} else {
													var num_of_feedback = 0;
												}
											}
											app.render('ultimate_user_summary.ejs', {
												status: 'ok',
												num_of_entries: num_of_entries,
												num_of_journey: num_of_journey,
												num_of_follower: num_of_follower,
												num_of_following: num_of_following,
												num_of_feedback: num_of_feedback
											}, function(err, html){
												if(err){
													log.error('Admin ultimate user summary - Admin %s - User %s - Error with %s'.red, req.session.user_name, user_id, err);
													res.send({
														status: "error"
													});
												}
												res.send({
													status: 'ok',
													contents: html
												});
											});
										}
									});
								}
							});
						}
					});
				}
			});
		}
	});

	/**
	 * Get Logs - TamTT
	 */
	app.post('/logs_ajax', function(req, res){
		if(!authentication_admin(req)){
			res.send({
				status: "error"
			});
		} else {
			var user_id = req.body.user_id;
			if(user_id == ''){
				res.send({
					status: 'ok',
					contents: ''
				});
			}
			if(app.is_deploy){
				s3Client.list({
					prefix: 'log'
				}, function(err, data){
					if(err){
						log.error('Admin logs - Admin %s - Error with %s'.red, req.session.user_name, err);
						res.send({
							status: "error"
						});
					}
					var list_log_file = [];
					for(var i = 1; i < data.Contents.length; i++){
						list_log_file.push(data.Contents[i].Key);
					}
					list_log_file.reverse().slice(0,40);
					var return_data = [];
					async.each(list_log_file, function(log_file, callback){
						s3Client.get('/' + log_file).on('response',function(res200){
							if(res200.statusCode == '404'){
							}
							res200.setEncoding('utf8');
							res200.on('data', function(chunk){
								return_data.push(chunk);
							});
							callback();
						}).end();
					}, function(err){
						if(err){
							log.error('Admin logs - Admin %s - Error with %s'.red, req.session.user_name, err);
							res.send({
								status: "error"
							});
						}
						app.render('logs.ejs', {
							status: 'ok',
							data: return_data
						}, function(err, html){
							if(err){
								log.error('Admin logs - Admin %s - Error with %s'.red, req.session.user_name, err);
								res.send({
									status: "error"
								});
							}
							res.send({
								status: 'ok',
								contents: html
							});
						});
					});
				});
			} else {
				res.send({
					status: 'ok',
					contents: 'Please access to local log folder (./log) to view log file!'
				});
			}
		}
	});
}